package com.bob.clan.wxconnector.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/***
 * 监听websocket地址  /myWs
 */
@ServerEndpoint("/myWs")
@Component
@Slf4j
@EnableScheduling
public class WsServerEndPointDemo {

    static Map<String, Session> map = new ConcurrentHashMap<String, Session>();

    /***
     * 连接建立时执行的操作
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        map.put(session.getId(), session);
        log.info("websocket is open");
    }

    /***
     * 收到客户端消息执行的操作
     * @param text
     */
    @OnMessage
    public String OnMessage(String text) {
        log.info("收到了一条信息" + text);
        return "已收到你的信息";
    }

    /***
     * 连接关闭时执行的操作
     * @param session
     */
    @OnClose
    public void OnClose(Session session) {
        map.remove(session.getId());
        log.info("连接关闭时执行的操作");
    }

    /***
     * 向客户端发送信息
     */
    @Scheduled(fixedRate = 2000)
    public void sendMsg() throws IOException {
        for (String key : map.keySet()) {
            map.get(key).getBasicRemote().sendText("你好，你好");
        }
    }
}
